/**
 * 语音识别服务
 * 实现浏览器语音识别和唤醒词检测功能
 */

class VoiceRecognitionService {
  constructor() {
    this.recognition = null;
    this.isListening = false;
    this.isContinuous = false;
    this.wakeWords = ['小智', '小智小智']; // 唤醒词列表，默认"小智"或"小智小智"
    this.wakeWordTimeout = 5000; // 唤醒后的有效时间（毫秒）
    this.wakeWordDetected = false; // 是否检测到唤醒词
    this.wakeWordTimer = null; // 唤醒词计时器
    this.language = 'zh-CN'; // 识别语言
    this.recognitionSupported = 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window;
    this.onListeningChange = null; // 监听状态变化回调
    this.onResult = null; // 识别结果回调
    this.onError = null; // 错误回调
    this.onWakeWordDetected = null; // 唤醒词检测回调
    this.onWakeWordTimeout = null; // 唤醒词超时回调
    this.resultBuffer = ''; // 用于存储连续识别的结果
    
    // 初始化语音识别
    this.initRecognition();
  }

  /**
   * 初始化语音识别
   */
  initRecognition() {
    if (!this.recognitionSupported) {
      console.warn('浏览器不支持语音识别');
      return;
    }

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    this.recognition = new SpeechRecognition();
    this.recognition.lang = this.language;
    this.recognition.continuous = false; // 开始时设为非连续模式
    this.recognition.interimResults = true; // 获取临时结果

    // 处理识别结果
    this.recognition.onresult = (event) => {
      const lastResult = event.results[event.results.length - 1];
      const transcript = lastResult[0].transcript.trim();
      
      // 检查是否包含唤醒词
      if (!this.wakeWordDetected) {
        // 检测唤醒词
        this.checkWakeWord(transcript);
      } else {
        // 已经唤醒，直接处理结果
        if (this.onResult) {
          this.onResult(transcript, lastResult.isFinal);
        }
        
        // 如果是最终结果，将其添加到结果缓冲中
        if (lastResult.isFinal) {
          this.resultBuffer += ' ' + transcript;
        }
      }
    };

    // 处理识别开始
    this.recognition.onstart = () => {
      this.isListening = true;
      if (this.onListeningChange) {
        this.onListeningChange(true);
      }
    };

    // 处理识别结束
    this.recognition.onend = () => {
      this.isListening = false;
      
      if (this.onListeningChange) {
        this.onListeningChange(false);
      }
      
      // 如果设置为连续模式，自动重新开始
      if (this.isContinuous) {
        this.start();
      } else if (this.wakeWordDetected) {
        // 如果唤醒词已激活但识别结束，处理结果缓冲
        if (this.resultBuffer.trim() && this.onResult) {
          this.onResult(this.resultBuffer.trim(), true);
        }
        this.resultBuffer = '';
      }
    };

    // 处理识别错误
    this.recognition.onerror = (event) => {
      console.error('语音识别错误:', event.error);
      
      if (this.onError) {
        this.onError(event.error);
      }
      
      this.isListening = false;
      if (this.onListeningChange) {
        this.onListeningChange(false);
      }
      
      // 如果是网络错误或设备错误，短暂延迟后尝试重新启动（如果是连续模式）
      if (this.isContinuous && ['network', 'service-not-allowed'].includes(event.error)) {
        setTimeout(() => this.start(), 3000);
      }
    };
  }

  /**
   * 检查文本是否包含唤醒词
   * @param {string} text 要检查的文本
   */
  checkWakeWord(text) {
    const normalizedText = text.toLowerCase();
    
    // 检查是否包含任何唤醒词
    const detected = this.wakeWords.some(word => normalizedText.includes(word.toLowerCase()));
    
    if (detected) {
      this.wakeWordDetected = true;
      
      // 清除之前的计时器（如果存在）
      if (this.wakeWordTimer) {
        clearTimeout(this.wakeWordTimer);
      }
      
      // 设置唤醒词超时计时器
      this.wakeWordTimer = setTimeout(() => {
        this.wakeWordDetected = false;
        
        if (this.onWakeWordTimeout) {
          this.onWakeWordTimeout();
        }
        
        // 如果设置为连续模式，继续监听
        if (this.isContinuous && !this.isListening) {
          this.start();
        }
      }, this.wakeWordTimeout);
      
      // 调用唤醒词检测回调
      if (this.onWakeWordDetected) {
        this.onWakeWordDetected(text);
      }
      
      // 重新启动识别以获取唤醒后的内容
      if (this.isListening) {
        this.stop();
        this.isContinuous = true; // 设置为连续模式以获取更多内容
        setTimeout(() => this.start(), 500);
      }
    }
  }

  /**
   * 设置唤醒词
   * @param {string[]} words 唤醒词数组
   */
  setWakeWords(words) {
    if (Array.isArray(words) && words.length > 0) {
      this.wakeWords = words;
    }
  }

  /**
   * 设置唤醒词超时时间
   * @param {number} timeout 超时时间（毫秒）
   */
  setWakeWordTimeout(timeout) {
    if (typeof timeout === 'number' && timeout > 0) {
      this.wakeWordTimeout = timeout;
    }
  }

  /**
   * 设置语言
   * @param {string} lang 语言代码（如'zh-CN'）
   */
  setLanguage(lang) {
    this.language = lang;
    if (this.recognition) {
      this.recognition.lang = lang;
    }
  }

  /**
   * 开始语音识别
   * @param {boolean} continuous 是否连续识别
   */
  start(continuous = false) {
    if (!this.recognitionSupported) {
      console.warn('浏览器不支持语音识别');
      return false;
    }
    
    if (this.isListening) {
      return true;
    }
    
    try {
      this.isContinuous = continuous;
      this.recognition.continuous = continuous;
      this.recognition.start();
      return true;
    } catch (error) {
      console.error('启动语音识别失败:', error);
      if (this.onError) {
        this.onError('启动失败');
      }
      return false;
    }
  }

  /**
   * 停止语音识别
   */
  stop() {
    if (this.isListening && this.recognition) {
      try {
        this.recognition.stop();
      } catch (error) {
        console.error('停止语音识别失败:', error);
      }
    }
  }

  /**
   * 重置语音识别状态（包括唤醒状态）
   */
  reset() {
    this.stop();
    this.wakeWordDetected = false;
    
    if (this.wakeWordTimer) {
      clearTimeout(this.wakeWordTimer);
      this.wakeWordTimer = null;
    }
    
    this.resultBuffer = '';
  }
}

// 创建单例
const voiceRecognition = new VoiceRecognitionService();

export default voiceRecognition; 